﻿using System.Text.Json;

namespace Journeo_backend.Services.Implementations
{
    public class CoordinateConversionService : ICoordinateConversionService
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly HttpClient _httpClient;
        private readonly string _amapKey;
        private const int BATCH_SIZE = 40; // 高德API单次请求最大支持40对坐标

        public CoordinateConversionService(ApplicationDbContext dbContext, HttpClient httpClient)
        {
            _dbContext = dbContext;
            _httpClient = httpClient;
            _amapKey = "109ce22db688316e0ff02c168e9c663f";
        }

        public async Task<Response<string>> ConvertBaiduToAmap()
        {
            try
            {
                // 从数据库中获取需要转换的坐标
                var attractions = await _dbContext.Attraction
                    .Where(a => a.Latitude != null && a.Longitude != null && a.AmapLatitude == null && a.AmapLongitude == null)
                    .ToListAsync();

                // 按批次处理坐标
                for (int i = 0; i < attractions.Count; i += BATCH_SIZE)
                {
                    var batch = attractions.Skip(i).Take(BATCH_SIZE).ToList();
                    await ProcessBatch(batch);
                    // 避免高德API调用频率过快
                    await Task.Delay(1000);
                }

                await _dbContext.SaveChangesAsync();

                return new Response<string>("success", "坐标转换成功");
            }
            catch (Exception e)
            {
                throw new Exception("Failed to convert coordinates", e);
            }
        }

        public async Task ProcessBatch(List<Attraction> attractions)
        {
            // 构建坐标字符串
            var locations = string.Join("|", attractions.Select(a =>
                $"{a.Longitude},{a.Latitude}"));

            // 构建API请求URL
            var url = $"https://restapi.amap.com/v3/assistant/coordinate/convert" +
                     $"?key={_amapKey}" +
                     $"&locations={locations}" +
                     "&coordsys=baidu";

            // 发送请求
            try
            {
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var content = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<AmapResponse>(content);

                if (result.status != "1")
                {
                    throw new Exception($"高德API返回错误: {result.info}");
                }

                // 解析返回的坐标
                var convertedLocations = result.locations.Split(';');

                // 更新数据库中的坐标
                for (int i = 0; i < attractions.Count; i++)
                {
                    var location = convertedLocations[i].Split(',');
                    attractions[i].AmapLongitude = decimal.Parse(location[0]);
                    attractions[i].AmapLatitude = decimal.Parse(location[1]);
                }

                await _dbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw new Exception($"处理批次坐标时发生错误: {ex.Message}", ex);
            }
        }
    }

    public class AmapResponse
    {
        public string status { get; set; }
        public string info { get; set; }
        public string infocode { get; set; }
        public string locations { get; set; }
    }
}
